package com.duoec.dw.lineage.service.analyser.expr;

import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr;
import com.duoec.dw.lineage.exceptions.LineageAnalyseException;
import com.duoec.dw.lineage.core.utils.AnalyserUtils;
import com.duoec.dw.lineage.dto.MultiTableLineageDto;
import com.duoec.dw.lineage.dto.TableFieldDependencyDto;
import com.duoec.dw.lineage.dto.TableFieldLineageDto;
import com.duoec.dw.lineage.dto.TableLineageDto;
import org.springframework.stereotype.Service;

import java.util.LinkedHashSet;

/**
 * @author xuwenzhen
 */
@Service
public class PropertyExprAnalyser extends BaseExprAnalyser<SQLPropertyExpr> {
    /**
     * 获取匹配类型
     *
     * @return 类型
     */
    @Override
    public Class<SQLPropertyExpr> getSqlExprType() {
        return SQLPropertyExpr.class;
    }

    /**
     * 分析表达式语句
     *
     * @param expr         表达式语句
     * @param fromLineages 当前语句from解析出来的血缘关系
     * @return 此表达式抽取出来的依赖
     */
    @Override
    public LinkedHashSet<TableFieldDependencyDto> analyse(SQLPropertyExpr expr, MultiTableLineageDto fromLineages) {
        String tableName = expr.getOwnernName();
        String fieldName = AnalyserUtils.formatFieldName(expr.getName());
        TableLineageDto table = fromLineages.getTable(tableName);
        if (table == null) {
            //找不到表，可能是struct字段
            LinkedHashSet<TableFieldDependencyDto> dependencies = fromLineages.searchByFieldName(tableName, (tableLineage, fieldLineage) -> {
                if (fieldLineage != null) {
                    return getDependencies(tableLineage, fieldLineage, tableName);
                }
                return null;
            });
            if (dependencies != null) {
                return dependencies;
            } else {
                throw new LineageAnalyseException("无法找到表:" + tableName);
            }
        }
        TableFieldLineageDto field = table.getField(fieldName);
        return getDependencies(table, field, fieldName);
    }
}
